/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xui_lib.util;

import ohos.agp.utils.Color;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

import com.xuexiang.xui_lib.XUI;

import java.io.IOException;
import java.util.Optional;

/**
 * 获取res中的资源
 *
 * @author xuexiang
 * @since 2018-12-18
 */
public class ResUtils {
    private ResUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 获取resources对象
     *
     * @return return
     */
    public static ResourceManager getResources() {
        return XUI.getContext().getResourceManager();
    }

    /**
     * 获取字符串
     *
     * @param resId 资源id
     * @return 对应的字符串
     */
    public static String getString(int resId) {
        try {
            return getResources().getElement(resId).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取颜色
     *
     * @param colorId 资源id
     * @return 对应的颜色
     */
    public static int getColor(int colorId) {
        try {
            return getResources().getElement(colorId).getColor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取颜色
     *
     * @param colorId 资源id
     * @return 对应的颜色
     */
    public static Color getFormatColor(int colorId) {
        return new Color(getColor(colorId));
    }

    /**
     * 获取颜色
     *
     * @param resId 资源id
     * @return 对应的颜色
     */
    public static float getFloat(int resId) {
        try {
            return getResources().getElement(resId).getFloat();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取字符串的数组
     *
     * @param resId 资源id
     * @return 资源数组
     */
    public static Optional<String[]> getStringArray(int resId) {
        try {
            return Optional.ofNullable(getResources().getElement(resId).getStringArray());
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        return Optional.empty();
    }
}
